﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Sandbox
{
    public static class ReflectionHelper
    {
        /// <summary>
        /// Returns the value of an object's field by name.
        /// </summary>
        public static Object GetFieldByName(Object target, String fieldName)
        {
            Type type = target.GetType();
            FieldInfo property = type.GetField(fieldName);
            return property.GetValue(target);
        }

        /// <summary>
        /// Returns the value of a private field by name.
        /// </summary>
        public static T GetPrivateFieldByName<T>(Object target, String fieldName)
        {
            Type type = target.GetType();
            FieldInfo property = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            return (T)property.GetValue(target);
        }

        /// <summary>
        /// Returns the value of an object's property (get) by name.
        /// </summary>
        public static Object GetPropertyByName(Object target, String propertyName)
        {
            Type type = target.GetType();
            PropertyInfo property = type.GetProperty(propertyName);
            return property.GetValue(target, null);
        }
    }
}
